package cn.edu.sasu;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.MessageQueue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import cn.edu.sasu.adapter.newsdetail.newsitem.NewsItemAdapter;
import cn.edu.sasu.domain.News;
import cn.edu.sasu.http.HttpNewsService;
import cn.edu.sasu.http.HttpUrl;
import cn.edu.sasu.utils.ActivityUtil;
import cn.edu.sasu.view.NewsListView;
import cn.edu.sasu.view.NewsListView.OnRefreshListener;

/**
 * 用户点击更多新闻里面的具体条目的时候，跳转到的页面Activity
 * <p>
 * 点击导航中剩下的导航
 * 
 * @author Administrator
 * 
 */
@SuppressLint("HandlerLeak")
public class NewsMoreItemActivity extends Activity {

	/**
	 * 后退的三角形，后退使用的
	 */
	private ImageButton btn_back = null;

	private TextView tv_title = null;

	private NewsListView listView = null;
	/**
	 * url路径
	 */
	private String url_title = null;
	/**
	 * 顶部动态文字
	 */
	private String title_text = null;

	private List<News> list = null;

	/**
	 * 新闻条目的适配器
	 */
	private NewsItemAdapter adapter = null;

	private ViewSwitcher viewSwitcher = null;

	private Map<String, String> params = null;
	private HttpNewsService newsService = null;
	private Button loadMoreButton = null;
	private ActivityUtil activityUtil = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_more_content);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			url_title = bundle.getString("more_news_list_url");
			title_text = bundle.getString("text");
		}
		init();
		requestRSSFeed();

	}

	private void init() {

		btn_back = (ImageButton) findViewById(R.id.btn_news_more_content_back);
		btn_back.setOnClickListener(onclick_listener);

		tv_title = (TextView) findViewById(R.id.tv_news_more_content_title);
		// 设置标题
		tv_title.setText(title_text);

		// 设置刷新按钮的初始图片
		loadMoreButton = new Button(this);
		loadMoreButton.setBackgroundResource(R.drawable.refresh1);
		loadMoreButton.setHint(21 + "");

		activityUtil = new ActivityUtil();
		loadMoreButton.setOnClickListener(loadMoreOnClickListener);

		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher_news_more_content);
		listView = new NewsListView(this);
		listView.setCacheColorHint(Color.argb(0, 0, 0, 0));
		listView.addFooterView(loadMoreButton);
		listView.setonRefreshListener(refreshListener);

		viewSwitcher.addView(listView);
		viewSwitcher.addView(getLayoutInflater().inflate(
				R.layout.progress_page, null));
		viewSwitcher.showNext();// 显示滚动条
		listView.setOnItemClickListener(listener);

		newsService = new HttpNewsService();
		params = new HashMap<String, String>();

	}

	private int startIndex = 0;
	private int endIndex = 0;

	private OnClickListener loadMoreOnClickListener = new View.OnClickListener() {

		@SuppressWarnings("static-access")
		@Override
		public void onClick(View v) {
			// 设置正在刷新的图片
			loadMoreButton.setBackgroundResource(R.drawable.refresh2);

			final AnimationDrawable rocketAnimation = (AnimationDrawable) loadMoreButton
					.getBackground();

			// 在Android4.0以前，这个方法是要放在操作主线程的UI中去做的，因为开始的时候，可能背景还没有绑定完成
			getMainLooper().myQueue().addIdleHandler(
					new MessageQueue.IdleHandler() {
						@Override
						public boolean queueIdle() {
							rocketAnimation.start();
							return false;
						}
					});

			startIndex = Integer.parseInt(loadMoreButton.getHint().toString());
			endIndex = startIndex + ActivityUtil.COUNT;

			new Thread() {
				@Override
				public void run() {
					list = activityUtil.nextPage(list, startIndex, endIndex,
							url_title);
					handler.sendEmptyMessage(3);
				}
			}.start();

		}
	};

	private OnRefreshListener refreshListener = new OnRefreshListener() {

		@SuppressWarnings("unchecked")
		@Override
		public void onRefresh() {
			new AsyncTask<Map<String, String>, Integer, List<News>>() {

				@Override
				protected List<News> doInBackground(
						Map<String, String>... params) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					data();
					return list;
				}

				@Override
				protected void onPostExecute(List<News> result) {
					loadMoreButton.setHint(21 + "");
					listView.setAdapter(new NewsItemAdapter(list,
							NewsMoreItemActivity.this));
					listView.onRefreshComplete();
				}

			}.execute();
		}
	};

	private void requestRSSFeed() {
		Thread t = new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					data();
					if (list.size() == 0) {
						handler.sendEmptyMessage(-1);
					} else {
						handler.sendEmptyMessage(1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}

	private void data() {
		params.clear();
		params.put("news.newsTitle", url_title);
		String data = newsService.requestByPost(
				HttpUrl.url(HttpUrl.NEWS_SELECT), params);

		list = newsService.parseNews(data);

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				adapter = new NewsItemAdapter(list, NewsMoreItemActivity.this);
				listView.setOnItemClickListener(listener);
				listView.setAdapter(adapter);
				viewSwitcher.showPrevious();// 显示新闻列表
			} else if (msg.what == 3) {
				if (list == null) {
					Toast.makeText(NewsMoreItemActivity.this,
							R.string.no_more_news, Toast.LENGTH_SHORT).show();
				} else {
					adapter.notifyDataSetChanged();// 刷新ListView
					loadMoreButton.setHint(endIndex + "");
					loadMoreButton.setText(getString(R.string.gong)
							+ list.size() + getString(R.string.tiao));
				}
				loadMoreButton.setBackgroundResource(R.drawable.refresh1);

			}
		};
	};

	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(NewsMoreItemActivity.this,
					NewsContentActivity.class);
			intent.putExtra("content_url", list.get(position - 1).getNewsId()
					+ "");
			intent.putExtra("count", list.get(position - 1).getCommentsCount()
					+ "");
			NewsMoreItemActivity.this.startActivityForResult(intent, position);
		}
	};

	/**
	 * 用户点击了后退的三角形的时候，直接关闭当前的这个Activity的就可以了，系统就会在任务栈中重启上一个Activity
	 */
	private OnClickListener onclick_listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			finish();
		}
	};
}
